//
//  ImageViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/11/28.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit

class ImageViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func setImage(image: UIImage) {
        setImageViewPosition(image: image)
        imageView.image = image
    }
    
    private func setImageViewPosition(image: UIImage) {
        
        let size = imageSizeWithScreen(image: image)
        imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        scrollView.frame = UIScreen.main.bounds
        scrollView.contentSize = size
        
        if size.height < scrollView.bounds.size.height {
            imageView.frame.origin.y = (scrollView.bounds.size.height - size.height) * 0.5
        }
    }
    
    private func imageSizeWithScreen(image:UIImage) -> CGSize {
        var size = UIScreen.main.bounds.size
        size.height = image.size.height * size.width / image.size.width
        return size
    }
}

extension ImageViewController: UIScrollViewDelegate {

    private func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    private func scrollViewDidZoom(_ scrollView: UIScrollView) {
        let originalSize = scrollView.bounds.size
        let contentSize = scrollView.contentSize
        let offsetX = originalSize.width > contentSize.width ? (originalSize.width-contentSize.width)/2 : 0
        let offsetY = originalSize.height > contentSize.height ? (originalSize.height-contentSize.height)/2 : 0
        self.imageView.center = CGPoint(x: contentSize.width/2+offsetX, y: contentSize.height/2+offsetY)
    }
}

